import { ApiResponse } from "apisauce"

import { apiSauce } from "@/services/api"
import { AgentModel } from "@/services/api/agents"

const CONVERSATION_PREFIX = "/gpt404/conv"

export interface BaseResp {
  code: number
}

export interface ConversationSummary {
  conversationId: string
  title: string
}

export interface ImageResource {
  url: string
  width?: number
  height?: number
}

export interface ImageCreation {
  imagePreview: ImageResource
  imageOrigin: ImageResource
}

export interface VideoCreation {}

export interface Creation {
  type: "image" | "video"
  state: "done" | "pending" | "failed"
  image?: ImageCreation
  video?: VideoCreation
}

export interface CreationBlock {
  creations: Creation[]
}

export interface ImageBlock {
  image: ImageResource
}

export interface TextBlock {
  text: string
}

export type ContentType = "text" | "image" | "creation"

export interface Content {
  contentType: ContentType
  textBlock?: TextBlock | null
  imageBlock?: ImageBlock | null
  creationBlock?: CreationBlock | null
}

export interface Message {
  conversationId?: string
  messageId?: string
  model: string
  contents: Content[]
  indexInConv?: number
  direction?: "ask" | "answer"
  state?: "done" | "pending" | "failed"
}

export interface EventData {
  message?: Message | null
}

export interface ServerSentEvent {
  id: number
  type: string
  data: EventData
  error?: any
}

export interface GetConversationsReq {
  last?: string
  size?: number
}

export interface GetConversationsData {
  conversations: ConversationSummary[]
  last: string
  hasMore: boolean
}

export interface GetConversationsResp extends BaseResp {
  data: GetConversationsData
}

export interface GetConversationReq {
  conversationId: string
  last?: string
  size?: number
}

export interface GetConversationData {
  messages: Message[]
  last: string
  hasMore: boolean
}

export interface GetConversationResp extends BaseResp {
  data: GetConversationData
}

export interface CompletionReq {
  messages: Message[]
}

export interface PixcatImageCreatedReq {
  id: number
  imageUrl: string
  fail?: boolean
  download?: string
  imageWidth?: number
  imageHeight?: number
}

export interface AddModelReq {
  model: string
}

export const getConversations = (
  params?: GetConversationsReq,
): Promise<ApiResponse<GetConversationsResp>> => {
  return apiSauce.get(`${CONVERSATION_PREFIX}/conversations`, params)
}

export const getConversation = (
  params: GetConversationReq,
): Promise<ApiResponse<GetConversationResp>> => {
  return apiSauce.get(`${CONVERSATION_PREFIX}/conversation`, params)
}

export const pixcatImageCreated = (
  payload: PixcatImageCreatedReq,
): Promise<ApiResponse<BaseResp>> => {
  return apiSauce.post(`${CONVERSATION_PREFIX}/pixcat_image_created`, payload)
}

export const addAgent = (payload: AddModelReq): Promise<ApiResponse<BaseResp>> => {
  return apiSauce.post(`${CONVERSATION_PREFIX}/model/add`, payload)
}
